/**
 * Created by jimmy on 2017/6/8.
 */

var logger = require('../lib/log').logger;
var async = require('async');
var wechat = require('../lib/wechat.js');
var config = require('../config/config.js');
var wxConfig = config['wechat'];
var userService = require("../service/UserService");
var wechatService = require("../service/WechatService");
var wxUtils = require("./WxUtil");
var tjs         = require('../lib/t.js');

exports.verifyUser = function (req,res,next,cb) {
    logger.debug(req.originalUrl);
    logger.debug("aaaaaa");
    if(req.originalUrl.indexOf("wxauth") == -1 && req.originalUrl.indexOf("paynotify") == -1 && req.originalUrl.indexOf("share") == -1){
        async.waterfall([
            function(callbk){
                if(req.session.openid != undefined){
                    userService.getWxUser(req.session.openid,callbk);
                }else {
                    callbk(null,[]);
                }
            },
            function(data,callbk){
                logger.debug(JSON.stringify(data));
                if(data.length == 0){
                    var wxurl = wxConfig.auth_url.replace('(appid)',wxConfig.appid)
                        .replace('(redirect_uri)',config['murl']+'/wx/wxauth')
                        .replace('(scope)', 'snsapi_userinfo')
                        .replace('(state)','index');
                    logger.debug(wxurl);
                    callbk({code:0,url:wxurl},null);
                } else{
                    req.session.nickname = data[0].nick_name;
                    req.session.openid = data[0].open_id;
                    req.session.head_img = data[0].head_img;
                    callbk(null,{code:0,msg:'OK'});
                }
            }
        ],function(err,result){
            if(err){
                logger.debug(err.url);
                cb(req,res,next,err,result);
            }else {
                cb(req,res,next,err,result);
            }
        });
    }else{
        console.log("asdqwqwfqvqdsa");
        cb(req,res,next,null,"ok");
    }
}

exports.getWxUser = function (req,res,next) {

}

exports.getAcctssToken = function (cb) {
    async.waterfall([
        function (cb) {
            wechatService.getToken(cb);
        },
        function (token,cb) {
            if(token.length == 0){
                wechat.getAccessToken(cb);
            }else {
                cb(null,{access_token:token[0].access_token})
            }
        },
        function (data,cb) {
            if(data['expires_in']) {
                wechatService.insToken(data.access_token, data.expires_in, function (err,dt) {
                    cb(null,{access_token:data.access_token});
                });
            }else {
                cb(null,{access_token:data.access_token});
            }
        }
    ],function (err,result) {
        cb(err,result);
    });
}

exports.getShareUrl = function (userId,cb) {
    async.waterfall([
        function (cb) {
            wechatService.getShareUrl(userId,cb);
        },
        function (url,cb) {
            if(url.length == 0) {
                wxUtils.getAcctssToken(cb);
            }else {
                cb(null,{ticket:url[0].ticket});
            }
        },
        function (data,cb) {
            if(data['access_token']) {
                var token = data.access_token;
                wechat.getShareUrl(token,userId,function (err,res) {
                    wechatService.insShareUrl(userId,res.ticket,res.expire_seconds,res.url,function (err,callback) {
                        cb(null,{ticket:res.ticket});
                    });
                });
            }else {
                cb(null,{ticket:data.ticket});
            }
        }
    ],function (err,result) {
        cb(err,result);
    });
}

exports.getWxConfig = function (openid,url,cb) {
    async.waterfall([
        function (cb) {
            wechatService.getJsTicket(cb);
        },
        function (ticket,cb) {
            if(ticket.length == 0) {
                wxUtils.getAcctssToken(cb);
            }else {
                cb(null,{ticket:ticket[0].jsticket});
            }
        },
        function (data,cb) {
            if(data['access_token']) {
                var token = data.access_token;
                wechat.getJsTicket(token,function (err,res) {
                    wechatService.insJsTicket(res.ticket,res.expires_in,function (err,callback) {
                        cb(null,{ticket:res.ticket});
                    });
                });
            }else {
                cb(null,{ticket:data.ticket});
            }
        }
    ],function (err,result) {
        if(!err){
            var nonceStr = Math.random().toString(36).substr(2, 15);
            var timeStamp = (+new Date()).toString().substr(0, 10);
            var wxconf = {
                appId:wxConfig.appid,
                timestamp:timeStamp,
                noncestr:nonceStr,
                signature:wxSign({
                    jsapi_ticket:result.ticket,
                    timestamp:timeStamp,
                    noncestr:nonceStr,
                    url:url
                })
            };
            console.log(wxconf)
            cb(err,{wxconf:wxconf});
        }else {
            cb(err,result);
        }
    });
}

function wxSign(args) {
    var keys = Object.keys(args);
    keys = keys.sort();
    var newArgs = {};
    keys.forEach(function (key) {
        newArgs[key] = args[key];
    });

    var string = '';
    for (var k in newArgs) {
        if(newArgs[k]=='')continue;
        string += '&' + k + '=' + newArgs[k];
    }
    string = string.substr(1);
    console.log("原串："+string);
    var sign = tjs.sha1(string);
    console.log('wx sign raw: '+string + '\n sign: '+sign);
    return sign;
}